import React, {SetStateAction, useEffect, useState} from "react";
import {Select} from "antd";
import {SelectProps} from "antd/lib/select";
import omit from "omit.js";
import {ApiResult} from "@/utils/data";

const {Option} = Select;

export interface DropDownListProps extends SelectProps<{}> {
  /** 是否显示全部 */
  all?: boolean;
  /** 全部文本值,默认为全部 */
  allText?: string;
  /** 下拉数据*/
  onLoad: () => Promise<ApiResult>;
}


/**
 * 数据字段组件-下拉菜单展示
 */
const DropDownList = function (props: DropDownListProps) {
  const {all, allText, onLoad} = props;
  const [list, setList] = useState<SetStateAction<any>>([]);

  /** 加载字典数据 */
  useEffect(() => {
    onLoad().then(r => {
      // 读取成功后设置数据对象
      if (r.success && r.data) {
        //设置编辑的数据
        setList(r.data);
      }
    });

  }, []);



  const inputProps = omit(props, ['dicCode', 'all', 'allText']);
  return (
    <Select
      filterOption={(input, option) =>
          option?.spell.toLowerCase().indexOf(input.toLowerCase()) >= 0
      }
      getPopupContainer={triggerNode => triggerNode.parentElement}
      {...inputProps}>
      {all && (<Option key="all" value="">{allText}</Option>)}
      {list.map((p:any) => <Option key={p.id} value={p.value} spell={p.spell}>{p.name}</Option>)}
    </Select>
  );
};
DropDownList.defaultProps = {all: false, allText: '全部'};

export default DropDownList;
